package univ.uchiha.esiag.gon.publisher;

import java.util.Vector;

import javax.rmi.PortableRemoteObject;

import org.omg.CORBA.ORB;
import org.omg.CORBA.Object;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;

import univ.uchiha.esiag.gon.broadcaster.BroadcasterLocal;
import univ.uchiha.esiag.gon.operation.Operation;
import univ.uchiha.esiag.gon.subscriber.Subscriber;


public class Publisher{
	private Semaphore semaphore;
	private Operation operation;
	private Vector<Subscriber> subscribers;
	private String topicName;
	public Publisher(String topicName, String[] subscribers) {
		semaphore = new Semaphore();
		operation = null;
		this.topicName = topicName;
		this.subscribers = new Vector<Subscriber>();
		for(int i = 0;i<subscribers.length;i++){
			ORB orb = BroadcasterLocal.getORB();
			try{
				POA rootPOA = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
				rootPOA.the_POAManager().activate();
				
				Object objRef = orb.string_to_object(subscribers[i]);
				Subscriber sub = (Subscriber)PortableRemoteObject.narrow(objRef, Subscriber.class);
				this.subscribers.add(sub);
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
	public void addSubcriber(Subscriber sub){
		subscribers.add(sub);
	}
	public String getTopicName() {
		return topicName;
	}
	public void put(Operation obj){
		if(operation != null)
			semaphore.stop();
		operation = obj;
		new Thread(new Runnable() {
			public void run() {
				for(int i = 0;i<subscribers.size();i++){
					try{
						subscribers.get(i).publish(operation);
					}catch(Exception e){
						e.printStackTrace();
					}
				}
				semaphore.signal();
			}
		}).start();
	}
}
